package com.ccBatis.exexutor;

import com.ccBatis.config.BoundSql;
import com.ccBatis.pojo.Configuration;
import com.ccBatis.pojo.MappedStatement;
import com.ccBatis.utils.GenericTokenParser;
import com.ccBatis.utils.ParameterMapping;
import com.ccBatis.utils.ParameterMappingTokenHandler;

import javax.sql.DataSource;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    private static Connection connection;
    private static PreparedStatement preparedStatement;

    private ResultSet resultSet;

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object param) {
        List<E> result = new ArrayList<>();
        try {
            connection = configuration.getDataSource().getConnection();
            String sql = mappedStatement.getSql();
            BoundSql boundSql = getBoundSql(sql);
            String finalSql = boundSql.getFinalSql();
            // 占位符进行替换
            preparedStatement = connection.prepareStatement(finalSql);

            List<ParameterMapping> list = boundSql.getList();
            String parameterType = mappedStatement.getParameterType();
            if (parameterType != null) {
                Class<?> paramterTypeClass = Class.forName(parameterType);
                for (int i = 0; i < list.size(); i++) {
                    // id
                    String paramName = list.get(i).getContent();
                    Field declaredField = paramterTypeClass.getDeclaredField(paramName);
                    declaredField.setAccessible(true);
                    Object o = declaredField.get(param);
                    // 赋值占位符
                    preparedStatement.setObject(i + 1, o);
                }
            }

            resultSet = preparedStatement.executeQuery();

            String resultType = mappedStatement.getResultType();
            Class<?> resultTypeClass = Class.forName(resultType);

            while (resultSet.next()) {
                ResultSetMetaData metaData = resultSet.getMetaData();
                Object o = resultTypeClass.newInstance();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = resultSet.getObject(columnName);
                    //属性描述器：通过api方法获取某个属性的set get方法
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(o, value);
                }
                result.add((E) o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    // 占位符替换
    private BoundSql getBoundSql(String sql) {
        // 创建标记处理器
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        // 创建标记解析器
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String finalSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(finalSql, parameterMappings);
        return boundSql;
    }

    @Override
    public void close() {

        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
